package com.lwl.nio.reg;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

//根据模式拆分字符串
public class Poodle {

	public static void main(String[] args) {
		String input = "poodle zoo";
		Pattern space = Pattern.compile(" ");
		Pattern d = Pattern.compile("d");
		Pattern o = Pattern.compile("o");
		Pattern[] patterns = { space, d, o };
		int limits[] = { 1, 2, 5, -2, 0 };
		if (args.length != 0) {
			input = args[0];
			patterns = collectPatterns(args);
		}
		generateTable(input, patterns, limits);
	}

	private static void generateTable(String input, Pattern[] patterns, int[] limits) {
		System.out.println("<?xml version='1.0'?>");
		System.out.println("<table>");
		System.out.println("\t<row>");
		System.out.println("\t\t<head>Input: " + input + "</head>");
		for (int i = 0; i < patterns.length; i++) {
			Pattern pattern = patterns[i];
			System.out.println("\t\t<head>Regex: <value>" + pattern.pattern() + "</value></head>");
		}
		System.out.println("\t</row>");
		for (int i = 0; i < limits.length; i++) {
			int limit = limits[i];
			System.out.println("\t<row>");
			System.out.println("\t\t<entry>Limit: " + limit + "</entry>");
			for (int j = 0; j < patterns.length; j++) {
				Pattern pattern = patterns[j];
				String[] tokens = pattern.split(input, limit);
				System.out.print("\t\t<entry>");
				for (int k = 0; k < tokens.length; k++) {
					System.out.print("<value>" + tokens[k] + "</value>");
				}
				System.out.println("</entry>");
			}
			System.out.println("\t</row>");
		}
		System.out.println("</table>");
	}

	/**
	 * If command line args were given, compile all args after the first as a
	 * Pattern. Return an array of Pattern objects.
	 */
	private static Pattern[] collectPatterns(String[] argv) {
		List<Pattern> list = new LinkedList<>();
		for (int i = 1; i < argv.length; i++) {
			list.add(Pattern.compile(argv[i]));
		}
		Pattern[] patterns = new Pattern[list.size()];
		list.toArray(patterns);
		return (patterns);
	}

}
